import React, { useState, useEffect } from 'react';
import axios from 'axios';

const AwardsForm = ({ applicationId }) => {
    const [awards, setAwards] = useState([]);
    const [newAward, setNewAward] = useState({
        awardType: '',
        awardName: '',
        awardDate: '',
        issuingDepartment: '',
        awardNumber: '',
        remarks: ''
    });
    const [editingId, setEditingId] = useState(null);

    useEffect(() => {
        const fetchAwards = async () => {
            try {
                const response = await axios.get(`/api/applications/${applicationId}/awards`);
                setAwards(response.data);
            } catch (error) {
                console.error('Error fetching awards:', error);
            }
        };

        if (applicationId) {
            fetchAwards();
        }
    }, [applicationId]);

    const handleChange = (e) => {
        const { name, value } = e.target;
        setNewAward(prevInfo => ({
            ...prevInfo,
            [name]: value
        }));
    };

    const handleAddOrUpdate = async (e) => {
        e.preventDefault();
        try {
            if (editingId) {
                await axios.put(`/api/applications/${applicationId}/awards/${editingId}`, newAward);
                alert('奖励信息更新成功！');
            } else {
                await axios.post(`/api/applications/${applicationId}/awards`, newAward);
                alert('奖励信息添加成功！');
            }
            setNewAward({
                awardType: '',
                awardName: '',
                awardDate: '',
                issuingDepartment: '',
                awardNumber: '',
                remarks: ''
            });
            setEditingId(null);
            const response = await axios.get(`/api/applications/${applicationId}/awards`);
            setAwards(response.data);
        } catch (error) {
            console.error('Error saving award:', error);
            alert('保存失败，请重试。');
        }
    };

    const handleEdit = (info) => {
        setNewAward(info);
        setEditingId(info.id);
    };

    const handleDelete = async (id) => {
        try {
            await axios.delete(`/api/applications/${applicationId}/awards/${id}`);
            alert('奖励信息删除成功！');
            setAwards(awards.filter(info => info.id !== id));
        } catch (error) {
            console.error('Error deleting award:', error);
            alert('删除失败，请重试。');
        }
    };

    return (
        <div className="form-container">
            <h3>奖励情况</h3>
            <form onSubmit={handleAddOrUpdate}>
                <div className="form-group">
                    <label>奖励类型:</label>
                    <input type="text" name="awardType" value={newAward.awardType} onChange={handleChange} required />
                </div>
                <div className="form-group">
                    <label>奖励名称:</label>
                    <input type="text" name="awardName" value={newAward.awardName} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>奖励日期:</label>
                    <input type="date" name="awardDate" value={newAward.awardDate} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>发证部门:</label>
                    <input type="text" name="issuingDepartment" value={newAward.issuingDepartment} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>奖励编号:</label>
                    <input type="text" name="awardNumber" value={newAward.awardNumber} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>备注:</label>
                    <textarea name="remarks" value={newAward.remarks} onChange={handleChange}></textarea>
                </div>
                <button type="submit">{editingId ? '更新' : '添加'}</button>
            </form>

            <h4>已添加奖励信息</h4>
            <table>
                <thead>
                    <tr>
                        <th>奖励类型</th>
                        <th>奖励名称</th>
                        <th>奖励日期</th>
                        <th>发证部门</th>
                        <th>奖励编号</th>
                        <th>备注</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {awards.map(info => (
                        <tr key={info.id}>
                            <td>{info.awardType}</td>
                            <td>{info.awardName}</td>
                            <td>{info.awardDate}</td>
                            <td>{info.issuingDepartment}</td>
                            <td>{info.awardNumber}</td>
                            <td>{info.remarks}</td>
                            <td>
                                <button onClick={() => handleEdit(info)}>编辑</button>
                                <button onClick={() => handleDelete(info.id)}>删除</button>
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
};

export default AwardsForm;

